﻿#include <pthread.h>
#include "httpCurl.h"
#include "httplib.h"

//-------------------------------------------------------------------------
mv::HttpCurlMgr *mv::HttpCurlMgr::_HttpCurlMgr = nullptr;
std::mutex http_mx;


//-------------------------------------------------------------------------

void log_callback(const httplib::Request& req, const httplib::Response& res) {
    std::cout << "发送一个请求：" << req.method << " " << req.path << std::endl;
    std::cout << "请求头信息：" << std::endl;
    for (auto it = req.headers.begin(); it != req.headers.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }
    std::cout << "请求体内容：" << req.body << std::endl;

    std::cout << "收到一个响应：" << res.status << std::endl;
    std::cout << "响应头信息：" << std::endl;
    for (auto it = res.headers.begin(); it != res.headers.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }
    std::cout << "响应体内容：" << res.body << std::endl;
}

mv::HttpCurlMgr *
mv::HttpCurlMgr::getSingleton(void)
{
	if (!_HttpCurlMgr)
	{
		std::lock_guard<std::mutex> locker(http_mx);
		_HttpCurlMgr = new mv::HttpCurlMgr;
	}
	return _HttpCurlMgr;
}

//-------------------------------------------------------------------------
void mv::HttpCurlMgr::destroyInstance(void)
{
	if (_HttpCurlMgr)
	{
		std::lock_guard<std::mutex> locker(http_mx);
		delete _HttpCurlMgr;
		_HttpCurlMgr = nullptr;
	}
}

std::string mv::HttpCurlMgr::httpPostFile(const std::string& filePath, const std::string& vehicleNo) {

	std::string strFile = getFileData(filePath);
	//httplib::Client cli(url.c_str());
	httplib::Client cli(m_sIP,m_iPort);

	//设置日志回调
	//cli.set_logger(log_callback);

	cli.set_read_timeout(20);
	cli.set_write_timeout(20);

	std::string fileName = filePath.substr(filePath.find_last_of('/') + 1);

	InfoL << "fileName: " << fileName;
	// InfoL << "buffer data: " << buffer.data();
	// httplib::MultipartFormDataItems items;
	// items.emplace_back("attachement", fileName, file, "application/octet-stream");
	// items.emplace_back("channelNo", channelNo, "", "");
	// items.emplace_back("vehicleNo", vehicleNo, "", "");
	    httplib::MultipartFormDataItems items = {
                //{ "attachement", filePath ,header,file_content_type},
				{ "attachement", strFile ,fileName,"application/octet-stream"},
				// { "channelNo", channelNo,"",""}, 
                // { "vehicleNo", vehicleNo,"",""},        
                { "channelNo", sChannelID,"form-data; name=\"channelNo\"",""}, 
                { "vehicleNo", vehicleNo,"form-data; name=\"vehicleNo\"",""},              
            };

 	// httplib::Headers headers;
    // headers.emplace("Content-Type", "multipart/form-data; boundary=" + httplib::detail::make_multipart_data_boundary());
	//auto res = cli.Post(m_sInterfacePath.c_str(),headers, items);
	auto res = cli.Post(m_sInterfacePath.c_str(),items);
	std::cout << "HTTP post" << std::endl;
    if (res && res->status == 200) {
        std::string body = res->body;
        std::cout << "HTTP request success" << std::endl;
		InfoL << "res body: " << body;
		Json::Value root;
		Json::Reader reader;
		if (!reader.parse(body, root))
			return "";
		bool value = root["success"].asBool();
		if (value) {
			return root["response"].asString();
		} else {
			return "";
		}
    } else {
        std::cout << "HTTP request failed" << std::endl;
        return "";
    }
}

void mv::HttpCurlMgr::setUploadPath(const std::string sPath, const std::string sIP, const int iPort) {
	sChannelID = getChannelID();
	InfoL << "setUploadPath: " << sChannelID;
	m_sInterfacePath = sPath;
	m_sIP = sIP;
	m_iPort = iPort;
}

//-------------------------------------------------------------------------
mv::HttpCurlMgr::HttpCurlMgr()
{
	//_serialMgr = nullptr;
	m_threadPoor = new ThreadPool(1);
}

//-------------------------------------------------------------------------
mv::HttpCurlMgr::HttpCurlMgr(const HttpCurlMgr &)
{
	//delete _serialMgr;
}